package com.wing.sell.controller.admin;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.sell.model.entity.AgentFollowRecord;
import com.wing.sell.model.request.AgentFollowRecordForm;
import com.wing.sell.model.response.AgentContactsVO;
import com.wing.sell.model.response.CustomerFollowResultTypeVO;
import com.wing.sell.model.response.CustomerFollowTypeVO;
import com.wing.sell.model.response.CustomerFollowWayVO;
import com.wing.sell.service.*;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-销售代理商经销跟进记录管理", tags = "#/sell/agentFollowRecord")
@RestController("agentFollowRecordController")
@RequestMapping("sell/admin/agentFollowRecord")
@RequiredArgsConstructor
@Slf4j
public class AgentFollowRecordController {

    private final AgentFollowRecordService agentFollowRecordService;
    private final CustomerFollowResultTypeService customerFollowResultTypeService;
    private final CustomerFollowTypeService customerFollowTypeService;
    private final CustomerFollowWayService customerFollowWayService;
    private final AgentContactsService agentContactsService;


    @ApiOperation(value = "查询所有销售代理商经销跟进记录", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "selAgtId", value = "跟进客户ID", defaultValue = "", example = "", dataType = "Long", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<AgentFollowRecord> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,Long selAgtId
    ){

        Page<AgentFollowRecord> pg = new Page<>(page, limit);
        QueryWrapper<AgentFollowRecord> queryWrapper = new QueryWrapper<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }

        //搜索
        if (selAgtId !=null){
            queryWrapper.eq("sel_agt_id", selAgtId);
        }

        IPage<AgentFollowRecord> list = agentFollowRecordService.getBaseMapper().selectPage(pg, queryWrapper);
        //关联相关业务属性
        list.getRecords().parallelStream().forEach(k -> {
            //跟进类型
            CustomerFollowTypeVO customerFollowTypeVO = customerFollowTypeService.get4appById(k.getFollowTypeId());
            if(null != customerFollowTypeVO) {
                k.setFollowTypeName(customerFollowTypeVO.getName());
            }
            //跟进方式
            CustomerFollowWayVO customerFollowWayVO = customerFollowWayService.get4appById(k.getFollowModelId());
            if(null != customerFollowWayVO){
                k.setFollowModelName(customerFollowWayVO.getName());
            }
            //跟进对象
            AgentContactsVO agentContactsVO = agentContactsService.get4appById(k.getContactsId());
            if(null != agentContactsVO){
                k.setContactsName(agentContactsVO.getName());
            }
            //跟进结果类型
            CustomerFollowResultTypeVO customerFollowResultTypeVO = customerFollowResultTypeService.get4appById(k.getFollowResultType());
            if(null != customerFollowResultTypeVO){
                k.setFollowResultTypeName(customerFollowResultTypeVO.getName());
            }
        });
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加销售代理商经销跟进记录", notes = "添加")
    @PostMapping("/add")
    public JsonResult add(@RequestBody AgentFollowRecordForm agentFollowRecordForm) {
        try {
            agentFollowRecordService.add(agentFollowRecordForm);
            return JsonResult.success("添加成功");
        }catch (Exception e){
            log.error("添加失败",e);
            return JsonResult.fail("添加失败"+e.getMessage());
        }

    }




    @ApiOperation(value = "修改销售代理商经销跟进记录", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@RequestBody AgentFollowRecordForm agentFollowRecordForm) {
        try{
            agentFollowRecordService.update(agentFollowRecordForm);
            return JsonResult.success("修改成功！");
        }catch (Exception e) {
            log.error("修改失败！",e);
            return JsonResult.fail("修改失败！"+e.getMessage());
        }
    }



    @ApiOperation(value = "删除销售代理商经销跟进记录", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "agentFollowRecordId", value = "销售代理商经销跟进记录id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long agentFollowRecordId) {
        if (agentFollowRecordService.removeById(agentFollowRecordId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "审核", notes = "审核")
    @GetMapping("/check")
    public JsonResult check(Long id) {
        AgentFollowRecord agentFollowRecord = this.agentFollowRecordService.getById(id);
        if(agentFollowRecord == null){
            return JsonResult.fail("审核失败！");
        }
        agentFollowRecord.setStatus(AgentFollowRecord.Status.check);
        agentFollowRecord.setCheckBy(JwtUtils.getLoginNickname());
        agentFollowRecord.setCheckById(JwtUtils.getLoginUserId());
        agentFollowRecord.setCheckTime(LocalDateTime.now());
        if (this.agentFollowRecordService.updateById(agentFollowRecord)) {
            return JsonResult.success("审核成功！");
        }
        return JsonResult.fail("审核失败！");
    }
}
